/**
 * 房间列表页面
 * 严格按照API接口文档实现
 */

const apiService = require('../../utils/apiService.js');
const authGuard = require('../../utils/authGuard.js');

Page({
  data: {
    // 页面状态
    loading: false,
    refreshing: false,
    hasMore: true,
    
    // 房间数据
    rooms: [],
    pinnedRooms: [],
    recentRooms: [],
    
    // 分页信息
    pagination: {
      total: 0,
      limit: 20,
      offset: 0,
      has_more: false
    },
    
    // 筛选条件
    filters: {
      type: 'all', // all, temporary, permanent
      status: 'all' // all, active, closed, expired
    },
    
    
    // 空状态
    isEmpty: false,
    emptyMessage: '暂无房间数据'
  },

  onLoad(options) {
    console.log('房间列表页面加载', options);
    
    // 检查登录状态
    const isLoggedIn = authGuard.onPageLoad('/pages/room-list/room-list');
    if (!isLoggedIn) {
      return;
    }
    
    // 初始化页面
    this.initPage();
  },

  onShow() {
    // 检查登录状态
    const isLoggedIn = authGuard.onPageShow('/pages/room-list/room-list', { silent: true });
    if (!isLoggedIn) {
      return;
    }
    
    // 刷新数据
    this.refreshData();
  },

  onPullDownRefresh() {
    console.log('下拉刷新');
    this.refreshData();
  },

  onReachBottom() {
    console.log('上拉加载更多');
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreRooms();
    }
  },


  /**
   * 初始化页面
   */
  async initPage() {
    try {
      this.setData({ loading: true });
      
      // 并行加载置顶房间和用户房间列表
      await Promise.all([
        this.loadPinnedRooms(),
        this.loadUserRooms()
      ]);
      
    } catch (error) {
      console.error('初始化页面失败:', error);
      this.showError('加载房间列表失败');
    } finally {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 刷新数据
   */
  async refreshData() {
    try {
      this.setData({ 
        refreshing: true,
        rooms: [],
        pinnedRooms: [],
        recentRooms: [],
        'pagination.offset': 0,
        hasMore: true
      });
      
      await this.initPage();
      
    } catch (error) {
      console.error('刷新数据失败:', error);
      this.showError('刷新失败');
    } finally {
      this.setData({ refreshing: false });
    }
  },

  /**
   * 加载置顶房间
   */
  async loadPinnedRooms() {
    try {
      const pinnedRooms = await apiService.getPinnedRooms();
      console.log('置顶房间加载成功:', pinnedRooms.length);
      
      this.setData({
        pinnedRooms: pinnedRooms || []
      });
      
    } catch (error) {
      console.error('加载置顶房间失败:', error);
      this.setData({
        pinnedRooms: []
      });
    }
  },

  /**
   * 加载用户房间列表
   */
  async loadUserRooms() {
    try {
      const params = {
        type: this.data.filters.type,
        status: this.data.filters.status,
        limit: this.data.pagination.limit,
        offset: this.data.pagination.offset
      };
      
      const result = await apiService.getMyRooms(params);
      console.log('用户房间列表加载成功:', result);
      
      const rooms = result.rooms || [];
      const pagination = result.pagination || {};
      
      this.setData({
        rooms: rooms,
        pagination: {
          total: pagination.total || 0,
          limit: pagination.limit || 20,
          offset: pagination.offset || 0,
          has_more: pagination.has_more || false
        },
        hasMore: pagination.has_more || false,
        isEmpty: rooms.length === 0
      });
      
    } catch (error) {
      console.error('加载用户房间列表失败:', error);
      this.setData({
        rooms: [],
        isEmpty: true,
        emptyMessage: '加载房间列表失败'
      });
    }
  },


  /**
   * 加载更多房间
   */
  async loadMoreRooms() {
    if (!this.data.hasMore || this.data.loading) {
      return;
    }
    
    try {
      this.setData({ loading: true });
      
      const params = {
        type: this.data.filters.type,
        status: this.data.filters.status,
        limit: this.data.pagination.limit,
        offset: this.data.pagination.offset + this.data.pagination.limit
      };
      
      const result = await apiService.getMyRooms(params);
      const newRooms = result.rooms || [];
      const pagination = result.pagination || {};
      
      this.setData({
        rooms: [...this.data.rooms, ...newRooms],
        pagination: {
          total: pagination.total || 0,
          limit: pagination.limit || 20,
          offset: pagination.offset || 0,
          has_more: pagination.has_more || false
        },
        hasMore: pagination.has_more || false
      });
      
    } catch (error) {
      console.error('加载更多房间失败:', error);
      this.showError('加载更多失败');
    } finally {
      this.setData({ loading: false });
    }
  },


  /**
   * 进入房间
   */
  async enterRoom(e) {
    console.log('enterRoom 方法被调用', e);
    const room = e.currentTarget.dataset.room;
    console.log('进入房间:', room);
    
    if (!room || !room.room_id) {
      console.error('房间信息不完整:', room);
      this.showError('房间信息不完整');
      return;
    }
    
    try {
      wx.showLoading({ title: '进入房间中...' });
      
      // 检查房间状态
      if (room.status === 'closed') {
        wx.hideLoading();
        wx.showModal({
          title: '房间已关闭',
          content: '该房间已关闭，无法进入',
          showCancel: false,
          confirmText: '确定'
        });
        return;
      }
      
      if (room.status === 'expired') {
        wx.hideLoading();
        wx.showModal({
          title: '房间已过期',
          content: '该房间已过期，无法进入',
          showCancel: false,
          confirmText: '确定'
        });
        return;
      }
      
      // 获取最新房间信息
      const roomInfo = await apiService.getRoomInfo(room.room_id);
      console.log('获取房间信息成功:', roomInfo);
      
      // 设置全局房间数据
      const app = getApp();
      const roomData = {
        roomId: roomInfo.room_id,
        roomTitle: roomInfo.title,
        roomType: roomInfo.type,
        roomDesc: roomInfo.description || '',
        participantCount: roomInfo.members_count || 1,
        currentRound: roomInfo.current_round || 1,
        status: roomInfo.status
      };
      
      app.globalData.currentRoom = roomData;
      
      // 更新首页房间数据
      this.updateHomePageRoomData(roomData);
      
      wx.hideLoading();
      
      // 跳转到点单页面
      wx.switchTab({
        url: '/pages/order/order'
      });
      
    } catch (error) {
      console.error('进入房间失败:', error);
      wx.hideLoading();
      
      if (error.statusCode === 404) {
        wx.showModal({
          title: '房间不存在',
          content: '该房间不存在或已被删除',
          showCancel: false,
          confirmText: '确定'
        });
      } else if (error.statusCode === 403) {
        wx.showModal({
          title: '权限不足',
          content: '您没有权限进入该房间',
          showCancel: false,
          confirmText: '确定'
        });
      } else {
        this.showError('进入房间失败，请重试');
      }
    }
  },

  /**
   * 更新首页房间数据
   */
  updateHomePageRoomData(roomData) {
    try {
      // 更新本地存储的房间数据
      const app = getApp();
      if (app.globalData.userRooms && app.globalData.userRooms.length > 0) {
        const updatedRooms = app.globalData.userRooms.map(room => {
          if (room.room_id === roomData.roomId) {
            return {
              ...room,
              members_count: roomData.participantCount,
              current_round: roomData.currentRound,
              status: roomData.status
            };
          }
          return room;
        });
        app.globalData.userRooms = updatedRooms;
        
        // 保存到本地存储
        wx.setStorageSync('userRooms', updatedRooms);
      }
    } catch (error) {
      console.error('更新首页房间数据失败:', error);
    }
  },

  /**
   * 切换房间置顶状态
   */
  async toggleRoomPin(e) {
    if (e && e.stopPropagation) {
      e.stopPropagation();
    }
    
    console.log('toggleRoomPin 方法被调用', e);
    const room = e.currentTarget.dataset.room;
    console.log('切换房间置顶状态:', room);
    
    if (!room || !room.room_id) {
      this.showError('房间信息不完整');
      return;
    }
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      if (room.is_pinned) {
        // 取消置顶
        await apiService.unpinRoom(room.room_id);
        wx.showToast({ title: '已取消置顶', icon: 'success' });
      } else {
        // 设置置顶
        await apiService.pinRoom(room.room_id);
        wx.showToast({ title: '已置顶', icon: 'success' });
      }
      
      // 刷新数据
      this.refreshData();
      
    } catch (error) {
      console.error('切换置顶状态失败:', error);
      this.showError('操作失败');
    } finally {
      wx.hideLoading();
    }
  },

  /**
   * 创建新房间
   */
  createRoom() {
    wx.navigateTo({
      url: '/pages/create-room/create-room'
    });
  },

  /**
   * 加入房间
   */
  joinRoom() {
    wx.navigateTo({
      url: '/pages/join-room/join-room'
    });
  },

  /**
   * 显示错误信息
   */
  showError(message) {
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    });
  },

});
